import React from "react";
import type { DataAction, IProTableRef } from "@yaf/pro-ui";
import { helper } from '@yaf/utils';

import {
  getRolePageList,
  createRole,
  updateRole,
  delRole,
  getRole,
} from "../../api";

interface FormatMenuData {
  pidToChildIdList: { [index: number]: number[] },
  childIdToPid: { [index: number]: number },
}

export const getDataAction = (proTableRef: React.MutableRefObject<IProTableRef>, formatMenuData: FormatMenuData): DataAction => {
  // 用于补全提交时，没有父级菜单的问题
  const formatSubmitMenuIds = (menuIds: number[]) => {
    const getAllPidList = (childMenuIdList: number[], parentMenuIdList: number[]) => {
      const newChildMenuIdList: number[] = [];

      childMenuIdList.forEach((menuId) => {
        const pid = formatMenuData.childIdToPid[menuId];
        if (pid) {
          newChildMenuIdList.push(pid);
          parentMenuIdList.push(pid)
        }
      });
      if (newChildMenuIdList.length > 0) {
        getAllPidList(newChildMenuIdList, parentMenuIdList);
      }

      return parentMenuIdList;
    }

    const newMenuIds = helper.uniq([...menuIds, ...getAllPidList(menuIds, [])]);

    return newMenuIds;
  }

  // 去掉子菜单没有选满的父级菜单
  const formatShowMenuIds = (menuIds: number[]) => {
    return menuIds.filter((pid) => {
      const childIdList = formatMenuData.pidToChildIdList[pid];
      if (childIdList) {
        const checkedChildIdList = childIdList.filter((childId) => menuIds.includes(childId));
        return checkedChildIdList.length == childIdList.length;
      }

      return true;
    });
  }

  return ({
    fetchList: (params) => {
      const { page, pageSize, filter } = params;
      return getRolePageList(Object.assign({ page, pageSize }, filter || {})).then((resp) => resp.data)
    },
    getItem: (rowKey) => {
      const roleId = rowKey as number;
      return getRole(roleId).then((resp) => {
        const { adminRole: role, menuIds } = resp.data;

        return { 
          name: role.name,
          type: role.type,
          allowUserUse: role.allowUserUse,
          listOrder: role.listOrder,
          remark: role.remark,
          menuIds: formatShowMenuIds([...menuIds]) 
        };
      })
    },
    createItem: (params) => {
      params.menuIds = formatSubmitMenuIds([...params.menuIds]);
      return createRole(params).then(() => proTableRef.current.doFetchList())
    },
    updateItem: (rowKey, params) => {
      const { name, type,allowUserUse, listOrder, remark, menuIds } = params;
      const newMenuIds = formatSubmitMenuIds([...menuIds]);
      return updateRole(rowKey as number, { name, type,allowUserUse, listOrder, remark, menuIds: newMenuIds }).then(() => proTableRef.current.doFetchList())
    },
    deleteItems: (selectedRowKeys) => {
      return delRole(selectedRowKeys.map((item) => parseInt(item)))
    },
  })
}




